// pages/logs/reg/index.js
const App = getApp();
import { hexMD5 } from "../../../utils/md5.js"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    userName: '',  // 用户名
    tel: '',  // 手机号
    verifyCode: '', // 验证码
    staff: '',  // 内部员工码
    password: '',  // 密码
    verifyNumber: 0,  // 是否获取过验证码
  },
  onLoad(){
    this.getCode();
  },
  getCode () {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('login:', res)
        this.setData({
          code: res.code
        })
      }
    })
  },

  bindGetUserInfo(e) {
    console.log('授权清空', e.detail.userInfo);
    // 判断空
    if (!this.data.userName) {
      App.prompts('用户名不能为空');
      return false;
    }
    if (!this.data.tel) {
      App.prompts('手机号不能为空');
      return false;
    }
    if (!this.data.verifyCode) {
      App.prompts('验证码不能为空');
      return false;
    }
    if (!this.data.staff) {
      App.prompts('内部员工码不能为空');
      return false;
    }
    if (!this.data.password) {
      App.prompts('新密码不能为空');
      return false;
    }

    let param = {
      code: this.data.code,
      verifyCode: this.data.verifyCode,
      tel: this.data.tel,
      real_name: this.data.userName,  // 真实姓名
      password: hexMD5(this.data.password),
      worker_no: this.data.staff
    };
    if (e.detail.userInfo) {
      let date = e.detail.userInfo;
      param.nick_name = date.nickName;
      param.head_img = date.avatarUrl;
    }
    let url = 'mp/user/register';
    App.ajax(url, 'POST', param).then(res => {
      console.log('注册返回', res)
      if (res.data.code) {
        // 存token
        wx.setStorage({
          key:"token",
          data: res.data.token
        });
        wx.switchTab({
          url: '/pages/index/index'
        });
      } else {
        this.getCode();
        App.prompts(res.msg);
      }
    }).catch(err => {
      this.getCode();
      console.log(err)
    })
  },

  // 自定义方法
  obtainCode() {
    if (!this.data.tel) {
      App.prompts('请输入手机号码');
      return false;
    }
    let url = 'open/sms/sendVerifyCode';
    App.ajax(url, 'POST', {tel: this.data.tel}).then(res => {
      console.log(res)
      this.setData({
        verifyNumber: 60
      })
      this.verifyFun();
    }).catch(err => {
      console.log(err)
    })
  },
  verifyFun() {
    setTimeout(() => {
      if (this.data.verifyNumber > 0) {
        this.setData({
          verifyNumber: this.data.verifyNumber -= 1
        })
        this.verifyFun();
      }
    }, 1000)
  },
  goLogin(e) {
    wx.navigateBack()
  },
  bindKeyInput(e) {
    let key = e.currentTarget.dataset.key;
    let date = {};
    date[key] = e.detail.value;
    this.setData(date);
  },
})